package com.customization.unionpay.market.workflowaction;

import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.dao.MarketAdvanceCtrlDao;
import com.customization.unionpay.market.dao.MarketAdvancePayDao;
import com.customization.unionpay.market.dao.WorkflowRequestbaseDao;
import com.customization.unionpay.market.maketEnum.InstructionEnum;
import com.customization.unionpay.market.util.FormDataUtils;
import com.engine.budget.service.impl.BusinessBudgetServiceImpl;
import weaver.general.BaseBean;
import weaver.generalledger.action.ZzgdExecuteInstrucitonAction;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.OverTimeSetBean;
import weaver.workflow.request.RequestManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MarketAdvanceRefundCheckAction extends BaseBean implements Action {
    private static final Logger log = LoggerFactory.getLogger(MarketAdvancePayCheckAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            RequestManager rm = requestInfo.getRequestManager();
            String loginid = rm.getUser().getLoginid();
            OverTimeSetBean overTimeSetBean = new OverTimeSetBean();
            int nodeId = rm.getNodeid();
            String nodeName = overTimeSetBean.getNodeName(nodeId);
            int requestid = rm.getRequestid();
            int formId = rm.getFormid();
            String tableName = rm.getBillTableName();
            //获取主笔明细
            Map<String, Object> tableInfo = FormDataUtils.getMainFormData(requestInfo);
            //获取子表核销预付明细
            List<Map<String, Object>> detailInfo = FormDataUtils.getDetailFormDataByIndex(1, requestInfo);
            //判断是否为大协议
            String sfwdxyId = tableInfo.get("sfwdxy").toString();
            String sfwdxyName = FormDataUtils.getItemName(formId, "sfwdxy", sfwdxyId);
            BusinessBudgetServiceImpl businessBudgetService = new BusinessBudgetServiceImpl();
            WorkflowRequestbaseDao workflowRequestbaseDao = new WorkflowRequestbaseDao();
            if ("否".equals(sfwdxyName)) {
                String xmbm = tableInfo.get("project_code").toString();
                Map<String, Double> map = new HashMap<>();
                for (Map<String, Object> dt : detailInfo) {
                    String yfkdh = dt.get("yfkdh").toString();
                    Double bcyfthje = Double.parseDouble(dt.get("bcyfthje").toString()) / 1000;
                    map.put(yfkdh, bcyfthje);
                }

                MarketAdvancePayDao marketAdvancePayDao = new MarketAdvancePayDao();
                List<JSONObject> advancePayList = marketAdvancePayDao.queryByXmbmAndBdh(xmbm, map);
                JSONObject insertJson = new JSONObject();
                for (JSONObject o : advancePayList) {
                    insertJson.put("budgetItem", o.getString("PROJECT_CODE"));
                    insertJson.put("budgetAccount", o.getString("yskm"));
                    insertJson.put("exeUnit", o.getString("yszrzx"));
                    insertJson.put("budgetPeriod", o.getString("ysqjn"));
//                    if (map.containsKey(o.getString("bdh"))) {
//                        String bcyfthje = map.get(o.getString("bdh"));}
                    insertJson.put("amount", map.get(o.getString("bdh")) / 1000);
                    //预付退回 被占用单据号传项目编号，执行单据号传表单号
                    insertJson.put("occDocNo", o.getString("PROJECT_CODE"));
                    insertJson.put("exeDocNo", o.getString("bdh"));
                    insertJson.put("budgetPostingPeriod", o.getString("yskzq"));
                    List<JSONObject> list = workflowRequestbaseDao.queryById(Integer.parseInt(o.getString("requestid")));
                    String zxrq = list.get(0).getString("zxrq");
                    insertJson.put("executionDate", zxrq);
                    insertJson.put("exeDocType", o.getString("ywlx"));
                    insertJson.put("claimant", o.getString("sqr"));
                    insertJson.put("sourceSystem", o.getString("lyxt"));
                    insertJson.put("remark", o.getString("sm"));
                    insertJson.put("reimbursementDept", o.getString("bzbm"));
                    insertJson.put("reimbursementCompany", o.getString("bzgs"));
                    insertJson.put("economicEvent", o.getString("jjsx"));
                    insertJson.put("event", "");
                    insertJson.put("instruction", "SF");

//                    Map<String, Object> params = new HashMap<>();
//                    params.put("params", Arrays.asList(insertJson));
//                    Map<String, Object> otherMap = new HashMap<>();
//                    otherMap.put("logId", requestid);
//                    otherMap.put("user", loginid);
//                    Map<String, Object> verify = businessBudgetService.verify(params, otherMap);
//                    JSONArray arr = JSONArray.parseArray(verify.get("result").toString());
//                    String status = arr.getJSONObject(0).getString("status");
//                    if ("1".equals(status)) {
//                        //todo
//                        MarketAdvanceCtrlDao marketAdvanceCtrlDao = new MarketAdvanceCtrlDao();
//                        marketAdvanceCtrlDao.insert(insertJson, requestid,tableName);
//                        businessBudgetService.execBudget(params, otherMap);
//                    }

                    String instruction = InstructionEnum.SFZY.toString();
                    MarketAdvanceCtrlDao marketAdvanceCtrlDao = new MarketAdvanceCtrlDao();
                    boolean result = marketAdvanceCtrlDao.insert(o, requestid, tableName);
                    if (!result) {
                        log.error("插入失败");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                    log.info("数据已插入中间表");
                    ZzgdExecuteInstrucitonAction zzgdExecuteInstrucitonAction = new ZzgdExecuteInstrucitonAction();
                    zzgdExecuteInstrucitonAction.setZl(instruction);

                    String execute = zzgdExecuteInstrucitonAction.execute(requestInfo);
                    log.info("预算释放调用结果：" + execute);
                    if ("0".equals(execute)) {
                        String messageid = requestInfo.getRequestManager().getMessageid();
                        log.info("messageid：" + messageid);
                        String messagecontent = requestInfo.getRequestManager().getMessagecontent();
                        log.info("messagecontent：" + messagecontent);
                        return Action.FAILURE_AND_CONTINUE;
                    } else {
                        log.info("预算释放调用成功！");
                    }

                }
            } else {

            }

        } catch (Exception e) {
            log.error("预付款退回单流程提交失败", e);
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }
}
